package it.traveldreamWeb.employee;

import it.traveldream.dto.DepartureDTO;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;


@FacesConverter(value="departureConverter")

public class DepartureConverter implements Converter {
	
	
	private static List<DepartureDTO> departures;
	
	public static void init(List<DepartureDTO> l){
		departures = new ArrayList<>(l);
	}
	

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String submittedValue) {
		 if (submittedValue.trim().equals(""))   
	            return null;  
	          
	        try{
	        	for (DepartureDTO d : departures){
	        		if (d.getDepartureId().equals(Long.decode(submittedValue)))
	        			return d;
	        	}
	        	return null;
	        } catch(Exception exception) {  
	            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid departure"));  
	        }    
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		String str = "";  
		if (value instanceof DepartureDTO)
        	str = "" + ((DepartureDTO)value).getDepartureId().toString();
        return str;
	}


	
	
	
}
